package com.kw.rabbittest.transaction.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import live.yanxiaohui.transaction.entity.SysUser;
import live.yanxiaohui.transaction.mapper.SysUserMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description todo
 * @CSDN https://blog.csdn.net/yxh13521338301
 * @Author： yanxh<br>
 * @Date 2020-06-29 11:21<br>
 * @Version 1.0<br>
 */
@Component
public class UserConsumer {

    @Autowired
    private SysUserMapper sysUserMapper;

    @RabbitListener(queues = "user_queue")
    public void consumer(Message message, Channel channel) throws Exception {
        String json = new String(message.getBody());
        SysUser user = JSONObject.parseObject(json, SysUser.class);
        String msgId = user.getMsgId();
        SysUser result = sysUserMapper.selectByMsgId(msgId);
        if (result != null) {
            System.out.println("数据已存在，无需补偿");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        int i = sysUserMapper.addUser(user);
        if (i > 0) {
            System.out.println("数据补充成功！");
            // 手动ack，通知mq删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } else {
            System.out.println("数据补偿失败");
        }
    }
}
